{% extends "base.html" %}

{% block head %}
<!-- 添加highlight.js库 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<!-- 添加常用语言包 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/bash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/yaml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/ini.min.js"></script>
{% endblock %}

{% block content %}
<style>
.file-viewer {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(25px);
    -webkit-backdrop-filter: blur(25px);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    padding: 2rem;
    box-shadow: 
        0 8px 32px rgba(0, 0, 0, 0.08),
        0 2px 8px rgba(0, 0, 0, 0.03),
        inset 0 1px 0 rgba(255, 255, 255, 0.15);
    position: relative;
    overflow: hidden;
}

/* Excel表格样式 */
.excel-container {
    margin-top: 20px;
    overflow-x: auto;
}

.excel-container table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.excel-container th {
    background-color: rgba(248, 249, 250, 0.1);
    font-weight: bold;
    text-align: left;
    padding: 10px;
    border: 1px solid rgba(222, 226, 230, 0.2);
}

.excel-container td {
    padding: 8px 10px;
    border: 1px solid rgba(222, 226, 230, 0.2);
}

.excel-container tr:nth-child(even) {
    background-color: rgba(248, 249, 250, 0.05);
}

.excel-container tr:hover {
    background-color: rgba(233, 236, 239, 0.1);
}

.file-viewer::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.12) 0%, rgba(255, 255, 255, 0.05) 50%, rgba(255, 255, 255, 0.02) 100%);
    pointer-events: none;
    z-index: 0;
    border-radius: 16px;
}

.file-viewer > div {
    position: relative;
    z-index: 1;
}

.file-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}

.file-title {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1C1C1E !important;
    margin: 0;
}

.file-info {
    color: #6c757d !important;
    font-size: 0.9rem;
}

.file-content {
    background: rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    padding: 0;
    font-family: 'Courier New', monospace;
    font-size: 0.9rem;
    line-height: 1.6;
    color: #1C1C1E !important;
    max-height: 600px;
    overflow-y: auto;
    position: relative;
}

.file-content pre {
    margin: 0;
    padding: 0;
}

.file-content code {
    white-space: pre;
    word-wrap: normal;
    padding: 1rem;
    display: block;
}

.line-numbers {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 3rem;
    background: rgba(0, 0, 0, 0.2);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
    padding: 1rem 0.5rem;
    text-align: right;
    color: rgba(255, 255, 255, 0.5);
    user-select: none;
}

.code-with-lines {
    margin-left: 3rem;
    padding: 1rem;
    overflow-x: auto;
}



.search-bar {
    display: flex;
    margin-bottom: 1rem;
    gap: 0.5rem;
}

.search-bar input {
    flex: 1;
    padding: 0.5rem;
    border-radius: 4px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    background: rgba(255, 255, 255, 0.1);
    color: inherit;
}

.search-bar button {
    padding: 0.5rem 1rem;
    border-radius: 4px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    background: rgba(255, 255, 255, 0.1);
    color: inherit;
    cursor: pointer;
}

.search-bar button:hover {
    background: rgba(255, 255, 255, 0.2);
}

.search-highlight {
    background-color: rgba(255, 255, 0, 0.3);
    border-radius: 2px;
}

.notice-content {
    background: rgba(255, 193, 7, 0.1);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 8px;
    padding: 1.5rem;
    text-align: center;
    color: #856404 !important;
    font-family: inherit;
    font-size: 1rem;
    line-height: 1.6;
}

.notice-content i {
    font-size: 2rem;
    margin-bottom: 1rem;
    display: block;
    color: #ffc107;
}

.btn-back {
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-weight: 500;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #1C1C1E !important;
    transition: all 0.3s ease;
}

.btn-back:hover {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    color: #1C1C1E !important;
    transform: translateY(-2px);
}

/* 暗黑模式适配 */
[data-theme="dark"] .file-viewer {
    background: rgba(0, 0, 0, 0.25);
    border-color: rgba(255, 255, 255, 0.15);
}

[data-theme="dark"] .file-viewer::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.04) 50%, rgba(255, 255, 255, 0.01) 100%);
}

[data-theme="dark"] .file-title {
    color: #ffffff !important;
}

[data-theme="dark"] .file-info {
    color: #bdc3c7 !important;
}

[data-theme="dark"] .file-content {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.1);
    color: #ffffff !important;
}

[data-theme="dark"] .line-numbers {
    background: rgba(0, 0, 0, 0.4);
    border-color: rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.4);
}

[data-theme="dark"] .notice-content {
    background: rgba(255, 193, 7, 0.15);
    border-color: rgba(255, 193, 7, 0.4);
    color: #ffc107 !important;
}

[data-theme="dark"] .btn-back {
    background: rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.15);
    color: #ffffff !important;
}

[data-theme="dark"] .btn-back:hover {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.2);
    color: #ffffff !important;
}

[data-theme="dark"] .search-bar input,
[data-theme="dark"] .search-bar button {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.15);
    color: #ffffff;
}

[data-theme="dark"] .search-bar button:hover {
    background: rgba(0, 0, 0, 0.4);
    border-color: rgba(255, 255, 255, 0.2);
}

[data-theme="dark"] .search-highlight {
    background-color: rgba(255, 215, 0, 0.3);
}
</style>

<div class="container mt-4">
    <div class="file-viewer">
        <div>
            <div class="file-header">
                <div>
                    <h2 class="file-title">
                        <i class="fas fa-file-code me-2"></i>
                        {{ filename }}
                    </h2>
                    <div class="file-info">
                        路径: {{ path }} | 大小: {{ size }} | 创建时间: {{ created }} | 修改时间: {{ modified }} | 编码: {{ encoding }}
                    </div>
                </div>
                <a href="{{ url_for('file_management', path=parent_path, user_id=target_user_id) }}" class="btn btn-back">
                    <i class="fas fa-arrow-left me-2"></i>返回
                </a>
            </div>
            
            {% if '不支持在线预览' in content or '文件过大' in content or '文件编码不支持' in content or 'Excel文件处理失败' in content %}
                <div class="notice-content">
                    <i class="fas fa-exclamation-triangle"></i>
                    {{ content }}
                </div>
            {% elif is_excel %}
                <div class="excel-container">
                    {{ excel_data|safe }}
                </div>
            {% else %}
                <div class="search-bar">
                    <input type="text" id="searchInput" placeholder="搜索文本..." />
                    <button id="prevMatch"><i class="fas fa-arrow-up"></i></button>
                    <button id="nextMatch"><i class="fas fa-arrow-down"></i></button>
                    <span id="matchInfo"></span>
                </div>
                <div class="file-content">
                    <div class="line-numbers" id="lineNumbers"></div>
                    <div class="code-with-lines">
                        <pre><code class="language-{{ extension }}">{{ content }}</code></pre>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 语法高亮
        document.querySelectorAll('pre code').forEach((block) => {
            hljs.highlightElement(block);
        });
        
        // 添加行号
        const codeBlock = document.querySelector('code');
        if (codeBlock) {
            const lineCount = codeBlock.innerHTML.split('\n').length;
            const lineNumbers = document.getElementById('lineNumbers');
            let lineNumbersHTML = '';
            for (let i = 1; i <= lineCount; i++) {
                lineNumbersHTML += i + '\n';
            }
            lineNumbers.textContent = lineNumbersHTML;
        }
        
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        const prevMatchBtn = document.getElementById('prevMatch');
        const nextMatchBtn = document.getElementById('nextMatch');
        const matchInfo = document.getElementById('matchInfo');
        let currentMatchIndex = -1;
        let matches = [];
        
        function performSearch() {
            // 清除之前的高亮
            document.querySelectorAll('.search-highlight').forEach(el => {
                const parent = el.parentNode;
                parent.replaceChild(document.createTextNode(el.textContent), el);
            });
            
            const searchTerm = searchInput.value.trim();
            if (!searchTerm) {
                matches = [];
                currentMatchIndex = -1;
                matchInfo.textContent = '';
                return;
            }
            
            // 获取代码内容
            const codeContent = codeBlock.textContent;
            
            // 查找所有匹配项
            matches = [];
            let match;
            const regex = new RegExp(searchTerm, 'gi');
            while ((match = regex.exec(codeContent)) !== null) {
                matches.push(match.index);
            }
            
            // 更新匹配信息
            matchInfo.textContent = matches.length > 0 ? 
                `${matches.length} 个匹配项` : '无匹配项';
            
            // 高亮匹配项
            if (matches.length > 0) {
                currentMatchIndex = 0;
                highlightCurrentMatch();
            } else {
                currentMatchIndex = -1;
            }
        }
        
        function highlightCurrentMatch() {
            if (currentMatchIndex >= 0 && currentMatchIndex < matches.length) {
                // 清除之前的高亮
                document.querySelectorAll('.search-highlight').forEach(el => {
                    const parent = el.parentNode;
                    parent.replaceChild(document.createTextNode(el.textContent), el);
                });
                
                // 高亮当前匹配项
                const matchIndex = matches[currentMatchIndex];
                const searchTerm = searchInput.value.trim();
                const codeContent = codeBlock.textContent;
                
                // 创建高亮元素
                const highlightSpan = document.createElement('span');
                highlightSpan.className = 'search-highlight';
                highlightSpan.textContent = codeContent.substring(matchIndex, matchIndex + searchTerm.length);
                
                // 替换文本节点
                const textNode = findTextNodeAtIndex(codeBlock, matchIndex);
                if (textNode) {
                    const beforeText = textNode.nodeValue.substring(0, matchIndex - getTextNodeOffset(textNode));
                    const afterText = textNode.nodeValue.substring(matchIndex - getTextNodeOffset(textNode) + searchTerm.length);
                    
                    const beforeTextNode = document.createTextNode(beforeText);
                    const afterTextNode = document.createTextNode(afterText);
                    
                    const parent = textNode.parentNode;
                    parent.replaceChild(afterTextNode, textNode);
                    parent.insertBefore(highlightSpan, afterTextNode);
                    parent.insertBefore(beforeTextNode, highlightSpan);
                    
                    // 滚动到可见区域
                    highlightSpan.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
                
                // 更新匹配信息
                matchInfo.textContent = `${currentMatchIndex + 1}/${matches.length} 个匹配项`;
            }
        }
        
        function findTextNodeAtIndex(element, targetIndex) {
            const textNodes = [];
            const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
            
            let currentNode;
            let currentIndex = 0;
            
            while ((currentNode = walker.nextNode())) {
                const nodeLength = currentNode.nodeValue.length;
                if (targetIndex >= currentIndex && targetIndex < currentIndex + nodeLength) {
                    return currentNode;
                }
                currentIndex += nodeLength;
            }
            
            return null;
        }
        
        function getTextNodeOffset(node) {
            let offset = 0;
            const walker = document.createTreeWalker(codeBlock, NodeFilter.SHOW_TEXT, null, false);
            
            let currentNode;
            while ((currentNode = walker.nextNode()) && currentNode !== node) {
                offset += currentNode.nodeValue.length;
            }
            
            return offset;
        }
        
        // 事件监听
        searchInput.addEventListener('input', performSearch);
        prevMatchBtn.addEventListener('click', () => {
            if (matches.length > 0) {
                currentMatchIndex = (currentMatchIndex - 1 + matches.length) % matches.length;
                highlightCurrentMatch();
            }
        });
        nextMatchBtn.addEventListener('click', () => {
            if (matches.length > 0) {
                currentMatchIndex = (currentMatchIndex + 1) % matches.length;
                highlightCurrentMatch();
            }
        });
    });
</script>
{% endblock %}